<template>
  <div class="app-container">
    <el-row :gutter="20" class="full-height clear-margin">
      <!--部门数据-->
      <el-col :span="4" :xs="24" class="full-height clear-padding" style="border-right: 1px solid #ddd">
        <div class="head-container" style="border-bottom: 1px solid #ddd">
          <el-input v-model="deptName"
                    placeholder="请输入部门名称"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"/>
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions"
                   :props="defaultProps"
                   node-key="deptCode"
                   highlight-current
                   :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   ref="tree"
                   default-expand-all
                   @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24" class="clear-padding">
        <div class="head-container flex-center" style="border-bottom: 1px solid #ddd;">
          <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item>用户管理</el-breadcrumb-item>
              <el-breadcrumb-item v-if="currentDept.deptName">{{currentDept.deptName}}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div style="text-align: right">
            <el-button type="primary"
                       plain
                       size="small"
                       v-has-permi="['system:user:insert']"
                       @click="handleAdd">新增用户
            </el-button>
            <el-button type="danger"
                       plain
                       size="small"
                       v-has-permi="['system:user:delete']"
                       :disabled="ids.length === 0"
                       @click="handleDelete">删除用户
            </el-button>
          </div>
        </div>

        <div class="body-container">
          <el-form :model="queryParams"
                   ref="queryForm"
                   class="queryForm"
                   :inline="true">
            <el-form-item label="查询用户：" prop="keywords">
              <el-input v-model="queryParams.keywords"
                        placeholder="请输入用户名称"
                        clearable
                        size="small"
                        @input="handleQuery"/>
            </el-form-item>
            <el-form-item label="状态：" prop="status">
              <Select v-model="queryParams.status"
                      size="small"
                      placeholder="请选择用户状态"
                      :options="statusOptions"
                      @change="selectQuery"/>
            </el-form-item>
            <el-form-item>

            </el-form-item>
          </el-form>

          <el-table v-loading="loading"
                    :data="userList"
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection"
                             width="55"/>
            <el-table-column label="用户编号"
                             width="220"
                             prop="userName"/>
            <el-table-column label="用户名称"
                             prop="name"
                             width="160"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="所属部门"
                             prop="dept.deptName"
                             width="160"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="手机号码"
                             prop="phone"
                             width="160"/>
            <el-table-column label="状态"
                             width="120"
                             :formatter="row => descriptionDictDataStatus(row.status, statusOptions)"/>
            <el-table-column label="创建时间"
                             prop="createTime"
                             width="220"
                             :formatter="row => dateFormatter(row)"/>
            <el-table-column label="操作">
              <template slot-scope="scope"
                        v-if="scope.row.userName !== 'admin'">
                <el-button size="small"
                           type="primary"
                           plain
                           v-has-permi="['system:user:update']"
                           @click="handleUpdate(scope.row)">编辑
                </el-button>
                <el-button size="small"
                           type="danger"
                           plain
                           v-has-permi="['system:user:delete']"
                           @click="handleDelete(scope.row)">删除
                </el-button>
                <el-dropdown size="mini"
                             @command="command => handleCommand(command, scope.row)">
                  <el-button size="small"
                             type="primary"
                             class="ml0"
                             v-has-permi="['system:user:update']"
                             plain>更多
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="handleResetPwd"
                                      icon="el-icon-key">重置密码
                    </el-dropdown-item>
                    <el-dropdown-item command="handleAuthRole"
                                      icon="el-icon-circle-check">分配角色
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>

      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title"
               :visible.sync="open"
               width="40%"
               top="20vh"
               :close-on-click-modal="false"
               append-to-body>
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户编号：" prop="userName">
              <el-input v-model="form.userName"
                        :disabled="form._id !== undefined"
                        placeholder="请输入用户编号"
                        maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门：" prop="dept">
              <treeselect v-model="form.dept"
                          :options="deptOptions"
                          :normalizer="normalizer"
                          :show-count="true"
                          placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码：" prop="phone">
              <el-input v-model="form.phone"
                        placeholder="请输入手机号码"
                        maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="form.email"
                        placeholder="请输入邮箱"
                        maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名：" prop="name">
              <el-input v-model="form.name"
                        placeholder="请输入用户姓名"
                        maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码："
                          v-if="form._id === undefined"
                          prop="password">
              <el-input v-model="form.password"
                        placeholder="请输入用户密码"
                        type="password"
                        maxlength="20"
                        show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别：">
              <Select v-model="form.gender"
                      style="width: 100%"
                      placeholder="请选择用户性别"
                      :options="sexOptions"></Select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model="form.remark"
                        type="textarea"
                        placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog title="分配角色" width="600px" :visible.sync="roleConfigDialog">

      <el-tree :data="roleOptions"
               :props="roleProps"
               node-key="_id"
               show-checkbox
               ref="roleTree"
               check-on-click-node
               default-expand-all/>

      <div slot="footer">
        <el-button type="primary" @click="roleConfigSure">确 认</el-button>
        <el-button type="default" @click="roleConfigDialog = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listUser, getUser, getInfo, delUser, addUser, updateUser, resetUserPwd} from "@/api/system/user"
  import {listDept} from "@/api/system/dept"
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  import {listRole} from "@/api/system/role"

  export default {
    name: "User",
    components: {Treeselect},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 选中名称
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        deptName: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "deptName"
        },
        // 角色树配置
        roleProps: {
          label: 'roleName',
          children: 'children'
        },
        // 角色树选项
        roleOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keywords: undefined,
          status: undefined,
        },
        // 表单校验
        rules: {
          userName: [
            {required: true, message: "用户编号不能为空", trigger: "blur"},
            {min: 2, max: 20, message: '用户编号长度必须介于 2 和 20 之间', trigger: 'blur'}
          ],
          name: [
            {required: true, message: "用户姓名不能为空", trigger: "blur"}
          ],
          password: [
            {required: true, message: "用户密码不能为空", trigger: "blur"},
            {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
          ],
          email: [
            {
              type: "email",
              message: "'请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        },
        // 分配角色弹框
        roleConfigDialog: false,
        // 当前角色信息
        currentUser: {},
        // 当前部门信息
        currentDept: {}
      }
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getList()
      this.getTreeselect()
      this.getRoleOptions()
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data
      })
      this.getDicts("sys_user_sex").then(response => {
        this.sexOptions = response.data
      })
    },
    methods: {
      /** 下拉框选择 */
      selectQuery(val) {
        if (val) this.queryParams.status = val
        else delete this.queryParams.status
        this.getList()
      },
      /** 查询用户列表 */
      getList() {
        this.loading = true
        listUser(this.queryParams).then(response => {
            this.userList = response.rows
            this.total = response.total
            this.loading = false
          }
        )
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, 'deptCode', 'parentCode')
        })
      },
      /** 查询角色下拉树结构 */
      getRoleOptions() {
        listRole().then(res => {
          this.roleOptions = res.rows
        })
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node._id,
          label: '[' + node.deptCode + '] ' + node.deptName,
          children: node.children
        }
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptCode = data.deptCode
        this.currentDept = data
        this.getList()
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          _id: undefined,
          dept: undefined,
          userName: undefined,
          password: '123456',
          phone: undefined,
          email: undefined,
          gender: undefined,
          name: undefined,
          status: "1",
          remark: undefined
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = []
        this.resetForm("queryForm")
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item._id)
        this.names = selection.map(item => item.name)
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row)
            break
          case "handleAuthRole":
            this.handleAuthRole(row)
            break
          default:
            break
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        // this.getTreeselect()
        getInfo().then(response => {
          this.open = true
          this.title = "添加用户"
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        getUser(row._id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改用户"
        })
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.name + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        }).then(({value}) => {
          this.$set(row, 'password', value)
          resetUserPwd(row._id, row).then(response => {
            this.msgSuccess("修改成功，新密码是：" + value)
          })
        }).catch(() => {
        })
      },
      /** 分配角色操作 */
      handleAuthRole(row) {
        this.roleConfigDialog = true
        const {_id: id} = row
        getUser(id).then(res => {
          this.currentUser = res.data
        }).then(() => {
          this.$refs.roleTree.setCheckedKeys(this.currentUser.roles)
        })
      },
      /** 分配角色确认弹框 */
      roleConfigSure() {
        const roles = this.$refs.roleTree.getCheckedKeys()
        this.currentUser.roles = roles
        updateUser(this.currentUser).then(res => {
          this.msgSuccess('保存成功')
          this.roleConfigDialog = false
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form._id != undefined) {
              updateUser(this.form).then(response => {
                this.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addUser(this.form).then(response => {
                this.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row._id ? [row._id] : this.ids
        const names = row.name ? [row.name] : this.names
        this.$confirm('是否确认删除用户姓名为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delUser(userIds)
        }).then(() => {
          this.getList()
          this.msgSuccess("删除成功")
        }).catch(() => {
        })
      },
    }
  }
</script>

<style lang="scss">
  .queryForm {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
</style>
